package com.piggymetrics.auth.service;

import com.gaea.tracker.ServiceTracker;
import com.piggymetrics.auth.domain.User;
import com.piggymetrics.auth.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

@Service
public class UserServiceImpl implements UserService {
	ThreadLocal<ServiceTracker> trackerThreadLocal = new ThreadLocal<ServiceTracker>();

	private final Logger log = LoggerFactory.getLogger(getClass());

	private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

	@Autowired
	private UserRepository repository;

	@Override
	public String create(User user) {
		if ( trackerThreadLocal.get() == null ){
			trackerThreadLocal.set(ServiceTracker.newInstance("auth-service"));
		}
		ServiceTracker tracker = trackerThreadLocal.get();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
						.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
						.getRequestAttributes()).getResponse();
		tracker.trackInEvent(request, response);

		User existing = repository.findOne(user.getUsername());
		Assert.isNull(existing, "user already exists: " + user.getUsername());

		String hash = encoder.encode(user.getPassword());
		user.setPassword(hash);

		repository.save(user);

		log.info("new user has been created: {}", user.getUsername());

		tracker.trackBackOutEvent(response);
		return "void";
	}
}
